<template>
  <div>
    <textarea :id="Id"></textarea>
  </div>
</template>
<script>
import axios from 'axios'
import tinymce from 'tinymce/tinymce'
import 'tinymce/icons/default/icons.min.js'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/importcss'
import 'tinymce/plugins/image'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/link'
import 'tinymce/themes/silver/theme'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/media'
export default {
  name: 'CustomEditor',
  props: {
    value: {
      default: '',
      type: String
    },
    config: {
      type: Object,
      default: () => {
        return {
          theme: 'silver'
        }
      }
    },
    url: {
      default: '',
      type: String
    },
    content: {
      default: '',
      type: String
    },
    accept: {
      default: 'image/jpeg, image/png',
      type: String
    },
    maxSize: {
      default: 2097152,
      type: Number
    },

    uploadType: {
      type: String,
      default: 'marketing'
    }
  },
  data () {
    const Id = Date.now()
    return {
      Id: Id,
      myEditor: null,
      defaultConfig: {
        menubar: 'false',
        statusbar: false,
        language_url: 'static/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: 'static/tinymce/skins/ui/oxide', // oxide-dark
        content_css: 'static/tinymce/skins/content/default/content.min.css',
        height: 400,
        toolbar: `
          styleselect |
          fontselect |
          formatselect |
          fontsizeselect |
          forecolor backcolor |
          bold italic underline strikethrough |
          insertfile link unlink |
          image table |
          alignleft aligncenter alignright alignjustify |
          outdent indent |
          numlist bullist |
          preview removeformat  hr |
          paste code advlist |
          insertdatetime
          undo redo |`,
        plugins: `
            paste
            importcss
            image
            code
            table
            advlist
            link
            lists
            hr
            preview
            insertdatetime
            media
          `,
        forced_root_block: 'p',
        force_p_newlines: true,
        importcss_append: true,
        content_style: `
            *                         { padding:0; margin:0; }
            html, body                { height:100%; margin:0;  }
            img                       { max-width:100%; display:block;height:auto; }
            a                         { text-decoration: none; }
            iframe                    { width: 100%; }
            p                         { line-height:1.6; margin: 0px; font-size: 14px; }
            table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
            .mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }
            ul,ol                     { list-style-position:inside; }
          `,
        insert_button_items: 'image link | inserttable',
        paste_retain_style_properties: 'all',
        paste_word_valid_elements: '*[*]',
        paste_data_images: true,
        paste_convert_word_fake_lists: false,
        // paste_webkit_styles: 'all',
        paste_merge_formats: true,
        nonbreaking_force_tab: false,
        paste_auto_cleanup_on_paste: false,
        toolbar_drawer: 'sliding',
        fontsize_formats: '10px 11px 12px 14px 16px 18px 20px 24px',
        style_formats: [
          {
            title: '首行缩进',
            block: 'p',
            styles: { 'text-indent': '2em' }
          },
          {
            title: '行高',
            items: [
              { title: '1', styles: { 'line-height': '1' }, inline: 'span' },
              { title: '1.5', styles: { 'line-height': '1.5' }, inline: 'span' },
              { title: '2', styles: { 'line-height': '2' }, inline: 'span' },
              { title: '2.5', styles: { 'line-height': '2.5' }, inline: 'span' },
              { title: '3', styles: { 'line-height': '3' }, inline: 'span' }
            ]
          }
        ],
        font_formats: `
            微软雅黑=微软雅黑;
            宋体=宋体;
            黑体=黑体;
            仿宋=仿宋;
            楷体=楷体;
            隶书=隶书;
            幼圆=幼圆;
            Andale Mono=andale mono,times;
            Arial=arial, helvetica,
            sans-serif;
            Arial Black=arial black, avant garde;
            Book Antiqua=book antiqua,palatino;
            Comic Sans MS=comic sans ms,sans-serif;
            Courier New=courier new,courier;
            Georgia=georgia,palatino;
            Helvetica=helvetica;
            Impact=impact,chicago;
            Symbol=symbol;
            Tahoma=tahoma,arial,helvetica,sans-serif;
            Terminal=terminal,monaco;
            Times New Roman=times new roman,times;
            Trebuchet MS=trebuchet ms,geneva;
            Verdana=verdana,geneva;
            Webdings=webdings;
            Wingdings=wingdings,zapf dingbats`,
        tabfocus_elements: ':prev,:next',
        object_resizing: true,
        imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions'
      }
    }
  },
  watch: {
    content: {
      handler () {
        this.myEditor.setContent(this.content)
      }
    }
  },
  methods: {
    getContent () {
      return this.myEditor.getContent()
    },
    init () {
      const self = this
      tinymce.init({
        selector: `#${this.Id}`,
        ...this.defaultConfig,
        // 图片上传
        images_upload_handler: function (blobInfo, success, failure) {
          if (blobInfo.blob().size > self.maxSize) {
            failure('文件体积过大')
          }
          if (self.accept.indexOf(blobInfo.blob().type) >= 0) {
            uploadPic()
          } else {
            failure('图片格式错误')
          }
          function uploadPic () {
            let formData = new FormData()
            formData.append('file', blobInfo.blob())
            axios.defaults.withCredentials = true // 配置为true
            axios.post(process.env.VUE_APP_API + '/attach/upload', formData, {
              headers: { // 添加请求头
                'Content-Type': 'multipart/form-data'
              }
            }).then(res => {
              let data = res.data
              if (data.flag) {
                success(data.data.realPath)
              } else {
                failure(data.message)
              }
            })
          }
        },
        ...this.config,
        setup: (editor) => {
          self.myEditor = editor
          editor.on(
            'init', () => {
              self.loading = true
              self.$emit('on-ready')
              // editor.setContent(self.value)
              self.loading = false
            }
          )
          editor.on(
            'input change undo redo', () => {
              self.$emit('input', editor.getContent())
            }
          )
        }
      })
    }
  },
  mounted () {
    this.init()
  },
  beforeDestroy () {
    // 销毁tinymce
    this.$emit('on-destroy')
    tinymce.remove(`#${this.Id}`)
  }
}
</script>
